import React, { PureComponent } from 'react';
import { connect, routerRedux } from 'dva';
import { ExclamationOutlined } from '@ant-design/icons';
import { Spin, Tooltip } from 'antd';
import uuid from 'es6-uuid';
import { PrimaryC, DATA_ENTRY, AdvancedSearch, ContentPackage, TableC } from '@/src/components';
import moment from 'moment';
import { renderChinese } from './counterparties/columnsData';
import './index.less';

class CounterpartyInfo extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1, // 当前页码
      pageSize: 20, // 每页条数
      orderByField: '', // 按某列排序
      order: '', // 升序降序 	 ascend升序，descend降序，不传，则表示默认，
      searchForm: '', // 搜索表单值
      sortedInfo: null, // 排序对象
      roleList: [], // 角色下拉列表
      countryList: [], // 国家地区下拉列表
      isUpdateFlag: '', // 是否更新标志位
      parentOrgList: [], // 母机构
    };
  }

  componentDidMount() {
    this.getTableData();
    this.props.dispatch({
      // 获取母机构
      type: 'counterpartyInformationM/getParentOrgList',
      payload: {
        id: '1',
      },
      callback: (params, type) => {
        if (type == 'success') {
          this.setState({
            ...params,
          });
        } else {
          c;
          this.setState({
            parentOrgList: [], // 母机构列表
          });
        }
      },
    });
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    if (sessionStorage.getItem('isUpdateFlag')) {
      // maat更新逻辑 ，只有跳转前存在storage里isUpdateFlag 才能进行更新
      sessionStorage.removeItem('isUpdateFlag'); // 更新完了清除isUpdateFlag标志
      this.getTableData();
    }
  }

  // 表格页码排序改变调用
  handleTableChange = (pagination, filter, sorter) => {
    const { current, pageSize } = pagination;
    this.setState(
      {
        currentPage: current,
        pageSize,
        sortedInfo: sorter, // 无法直接使用sorter里的变量赋值，否则排序状态有问题，需要配合使用sortOrder
      },
      () => {
        this.getTableData();
      },
    );
  };

  goToDetail = (id, type) => {
    // maat环境的用户跳转
    if (type != 'add') {
      // 保存交易对手id
      if (type == 'edit') {
        sessionStorage.setItem('counterpartiesID_edit', id);

        this.props.dispatch(routerRedux.push(`/counterpartyManagement/counterpartyInfoEdit?id=${uuid(32)}`));
      } else {
        // 详情跳转 保存交易对手id 更新标志位
        sessionStorage.setItem('counterpartiesID', id);
        sessionStorage.setItem('isQueryUpdate', 1);
        this.props.dispatch(routerRedux.push(`/counterpartyManagement/counterpartyInfoQuery`));
        this.props.dispatch({
          // 只是为了让props有变动
          type: 'counterpartyInformationM/setState',
          payload: {
            id,
          },
        });
      }
      return;
    }
    this.props.dispatch(routerRedux.push(`/counterpartyManagement/counterpartyInfoAdd`));
  };

  // 查询列表数据
  getTableData = () => {
    const { dispatch } = this.props;
    const { pageSize, currentPage, searchForm } = this.state;
    const sortedInfo = this.state.sortedInfo ? this.state.sortedInfo : {};
    if (sortedInfo && sortedInfo.column && sortedInfo.column.sorter !== true) return; // 非排序字段不进行请求
    const apiParams = {
      numInPage: pageSize,
      currentPage,
      orderByField: sortedInfo.field || '',
      order: sortedInfo.order || '',
      ...searchForm,
      countries: searchForm.countries ? searchForm.countries.join(',') : '',
      role: searchForm.role ? searchForm.role.join(',') : '',
    };

    this.props.dispatch({
      type: 'counterpartyInformationM/queryCounterpartyList',
      payload: {
        ...apiParams,
      },
    });
  };

  remove = (id, name) => {
    //  点击删除
    const { currentPage } = this.state;
    const {
      counterpartyInformationM: {
        tableData: { dataSource = [] },
      },
    } = this.props;
    this.props.dispatch({
      type: 'counterpartyInformationM/deleteCounterparty',
      payload: {
        id,
      },
      callback: (msg) => {
        if (msg) {
          const arr = dataSource.filter((item) => {
            return item.id != id;
          });
          if (!arr.length && currentPage != 1) {
            // 非首页列表数据删除完之后，重置页码为首页
            this.setState(
              {
                currentPage: 1,
              },
              () => {
                this.getTableData();
              },
            );
          } else {
            this.getTableData();
          }
        }
      },
    });
  };

  renderTable = () => {
    const { pageSize, currentPage, shortArrs } = this.state;
    let { sortedInfo } = this.state;
    const {
      loading,
      counterpartyInformationM: { tableData },
      userM: { currentUser },
      globalM: {
        dataDictionary: { COUNTERPARTY_AVAILABLE_STATUS_DICT = [], COUNTER_PARTY_ROLE = [], COUNTER_PARTY_COUNTRY = [] },
      },
    } = this.props;
    // 判断岗位信息是否是交易员
    const isTrader = currentUser.stationModels?.some((v) => v.postName === '交易员');

    const { parentOrgList } = this.state;
    sortedInfo = sortedInfo || {};
    const availableList = COUNTERPARTY_AVAILABLE_STATUS_DICT.map((item) => {
      return {
        value: item.code,
        title: item.value,
      };
    });
    const columns = tableData.columns || [];
    columns.map((item, key) => {
      item.dataIndex = item.key;
      if (item.key == 'missing') {
        item.render = (text) => {
          item.width = '20px';
          const htmlContent =
            text == '1' ? (
              <span className='missIcon'>
                <Tooltip title='当前条目必填字段缺失，需要将信息补充完整'>
                  <ExclamationOutlined />
                </Tooltip>
              </span>
            ) : (
              ''
            );
          return htmlContent;
        };
      }
      // if (item.key != 'parentOrg' && item.key != 'role' && item.key != 'operate') {
      //   item.sorter = true;
      //   item.sortOrder = sortedInfo.columnKey === item.key && sortedInfo.order
      // }
      if (item.key == 'parentOrg') {
        item.render = (text) => {
          return <span>{renderChinese(text, parentOrgList)}</span>;
        };
      }
      if (item.key == 'parentOrg') {
        item.width = '100px';
      }
      if (item.key == 'role') {
        item.width = '105px';
      }
      if (item.key == 'countries') {
        item.width = '80px';
        item.render = (text) => {
          return <span>{renderChinese(text, COUNTER_PARTY_COUNTRY)}</span>;
        };
      }
      if (item.key == 'isProduct') {
        item.width = '100px';
        item.render = (text) => {
          return <span>{text == '0' ? '是' : '否'}</span>;
        };
      }
      if (item.key == 'timeOfExpiration') {
        item.align = 'right';
        item.width = '100px';
        item.render = (text) => {
          return moment(text).format('YYYY-MM-DD');
        };
      }
      if (item.key == 'role') {
        item.render = (text) => {
          const arr = [];
          text.split(',').map((item) => {
            arr.push(renderChinese(item, COUNTER_PARTY_ROLE));
          });
          return <span>{arr.join(',')}</span>;
        };
      }
      if (item.key == 'status') {
        item.render = (text, record) => {
          return text !== null ? renderChinese(text, availableList) : '--';
        };
      }
    });
    // 因为columns来自props，会不停的渲染添加操作列，在此做一下判断
    if (columns.length && columns[columns.length - 1].title != '操作') {
      columns.push({
        title: '操作',
        key: 'operate',
        width: 196,
        sorter: false,
        // type: 'operate',
        render: (_, record) => {
          return (
            <div>
              <a onClick={(e) => this.goToDetail(record.id, 'query', e)}>查看</a>
              <a
                disabled={isTrader ? false : record.status !== '1'}
                style={isTrader ? {} : record.status !== '1' ? { cursor: 'not-allowed' } : {}}
                onClick={(e) => {
                  e.preventDefault();
                  if (isTrader) {
                    this.goToDetail(record.id, 'edit', e);
                  } else {
                    record.status == '1' && this.goToDetail(record.id, 'edit');
                  }
                }}
              >
                修改
              </a>
              <a
                disabled={isTrader ? false : record.status !== '1'}
                style={isTrader ? {} : record.status !== '1' ? { cursor: 'not-allowed' } : {}}
                onClick={(e) => {
                  e.preventDefault();
                  if (isTrader) {
                    this.remove(record.id, record.shortName);
                  } else {
                    record.status == '1' && this.remove(record.id, record.shortName);
                  }
                }}
              >
                删除
              </a>
            </div>
          );
        },
        // operates: [
        //   {
        //     title: '查看',
        //     onClick: (record, index) => this.goToDetail(record.id, 'query'),
        //   },
        //   {
        //     title: '修改',
        //     onClick: (record, index) => this.goToDetail(record.id, 'edit'),
        //     rules: {
        //       disabled: { relation: 'and', items: [{ key: 'status', value: ['1'], relation: ['!='] }] },
        //     },
        //   },
        //   {
        //     title: '删除',
        //     onClick: (record, index) => this.remove(record.id, record.shortName),
        //     rules: {
        //       disabled: { relation: 'and', items: [{ key: 'status', value: ['1'], relation: ['!='] }] },
        //     },
        //   },
        // ],
      });
    }
    return (
      <div>
        <Spin spinning={loading.effects['counterpartyInformationM/queryCounterpartyList'] == true}>
          <TableC
            columns={columns}
            dataSource={tableData.dataSource || []}
            onChange={this.handleTableChange}
            current={currentPage}
            selfScrollY={true}
            pageSize={pageSize}
            total={(tableData.pageInfo && tableData.pageInfo.total) || 0}
            rowKey='id'
          />
        </Spin>
      </div>
    );
  };

  render() {
    const {
      globalM: {
        dataDictionary: { COUNTER_PARTY_COUNTRY = [], COUNTER_PARTY_ROLE = [] },
      },
    } = this.props;

    const countryList = COUNTER_PARTY_COUNTRY.map((item) => {
      return {
        value: item.code,
        title: item.value,
      };
    });
    const roleList = COUNTER_PARTY_ROLE.map((item) => {
      return {
        value: item.code,
        title: item.value,
      };
    });
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'shortName',
          title: '交易对手短名',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'longName',
          title: '交易对手长名',
          type: DATA_ENTRY.INPUT,
        },
        {
          dataIndex: 'countries',
          title: '国家地区',
          type: DATA_ENTRY.SELECT,
          dataSource: countryList,
          allowClear: true,
          isMultiple: true,
        },
        {
          dataIndex: 'role',
          title: '交易对手角色',
          type: DATA_ENTRY.SELECT,
          dataSource: roleList,
          allowClear: true,
          isMultiple: true,
        },
        {
          dataIndex: 'creator',
          title: '创建人',
          type: DATA_ENTRY.INPUT,
        },
      ],
      onQuery: (e) => {
        this.setState(
          {
            searchForm: { ...e },
            currentPage: 1, // 点击查询按钮重置为第一页
          },
          () => {
            this.getTableData();
          },
        );
      },
      onClear: () => {
        // 重置查询条件
        this.setState(
          {
            currentPage: 1,
            pageSize: 20,
            orderByField: '',
            order: '',
            searchForm: '',
            sortedInfo: null,
          },
          () => {
            this.getTableData();
          },
        );
      },
    };
    return (
      <ContentPackage
        title='交易对手基础信息'
        contentHtml={
          <div className='counterpartyInfo'>
            <AdvancedSearch {...searchProps} />
            <div className='addCounterparty'>
              <PrimaryC onClick={() => this.goToDetail('', 'add')} title='新增' />
            </div>
            {this.renderTable()}
          </div>
        }
      />
    );
  }
}

export default connect(({ counterpartyInformationM, globalM, tradingCompanyM, loading, userM }) => ({
  counterpartyInformationM,
  globalM,
  tradingCompanyM,
  loading,
  userM,
}))(CounterpartyInfo);
